#include "sqlquerymodel.h"
#include <QSqlField>
#include <QDebug>

SqlQueryModel::SqlQueryModel(QObject *parent) :
    QSqlQueryModel(parent)
{
}

void SqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db)
{
    QSqlQueryModel::setQuery(query, db);
    generateRoleNames();
}

void SqlQueryModel::setQuery(const QSqlQuery & query)
{
    QSqlQueryModel::setQuery(query);
    generateRoleNames();
}

void SqlQueryModel::generateRoleNames()
{
    m_roleNames.clear();
    for( int i = 0; i < record().count(); i ++) {
        m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
    }
}

QVariant SqlQueryModel::data(const QModelIndex &index, int role) const
{
    QVariant value;
    if(role <= Qt::UserRole) {
        value = QSqlQueryModel::data(index, role);
    }
    else {
        int columnIdx = role - Qt::UserRole - 1;
        QModelIndex modelIndex = this->index(index.row(), columnIdx);
        value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
    }
    return value;
}

QList<QVariant> SqlQueryModel::getData(const int &row)
{
    QList<QVariant> value;
    for(int i=0;i<record().count();i++)
    {
        QModelIndex modelIndex = this->index(row, i);
        value <<QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
    }
    return value;
}

void SqlQueryModel::delCurIndexData(const int &row)
{
    QVariant m_id;
    QModelIndex modelIndex = this->index(row,0);  //对应行的第一列   id
    m_id=QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
    QString query1=QString("delete  from PatientBaseInfo where PatientID='%1'").arg(m_id.toString());
    setQuery(query1);
    setQuery("select * from PatientBaseInfo");
}

void SqlQueryModel::delAllData()
{
    QString query1=QString("delete  from PatientBaseInfo ");
    setQuery(query1);
}

void SqlQueryModel::insertData(const QString &id)
{
    QString query1=QString("insert into PatientBaseInfo (PatientID,PatientName,PatientGender,PatientBrithday) values('%1','女','0')").arg(id);
    setQuery(query1);
    setQuery("select * from PatientBaseInfo");
}


